import React, { useContext, useEffect, useState, useRef } from 'react';
import { contAppInfo } from 'context/appInfo';
import styles from './index.less';
import { LeftOutline, RightOutline } from 'antd-mobile-icons';
import PdfViewer from './pdfViewer/index';
import copy from 'copy-to-clipboard';
//@ts-ignore
import * as pdfjsLib from 'pdfjs-dist';
//@ts-ignore
import { saveAs } from 'file-saver';
import { Button, Modal, Space, Swiper, Toast, CapsuleTabs, Dialog, ImageViewer, Image } from 'antd-mobile';
import { SwiperRef } from 'antd-mobile/es/components/swiper';
import { laputaTrack, laputaTrackHOC } from '@jdh/laputa-sdk';

const ExposureTestItem = laputaTrackHOC((props: any) => {
  const { index, item } = props;
  return (
    <div style={{ height: '150px' }}>
      <span>{index}</span>
      <span>{item.text}</span>
    </div>
  );
});

const BbcInvoiceDetail = (props: any) => {
  const { floor, mpaas_sdk, label, children } = props;
  const { cfg, api } = floor || {};
  const { EventBus, getSearchAndParams } = mpaas_sdk || {};
  const ref = useRef<SwiperRef>(null);
  const appInfo = useContext(contAppInfo);
  const { bbcShopId, orderId } = getSearchAndParams();
  const [busData, setBusData] = useState<any>();
  const [patientList, setPatientList] = useState<any>([]);
  const [pathList, setPathList] = useState<any>([]); // 存发票链接
  const [tabKey, setTabKey] = useState('0');
  const [pdfVisible, setPdfVisible] = useState(false);
  const [imageSrc, setImageSrc] = useState(''); // 保存图片URL
  const [imageViewerVisible, setImageViewerVisible] = useState(false); // 控制ImageViewer的显示

  useEffect(() => {
    console.log(cfg, api, EventBus, appInfo, children);
    console.log('=================>>>>change floor', floor);
  }, [floor]);

  useEffect(() => {
    api.queryOrderInvoice({
      bbcShopId,
      orderId,
    }).then((res: any) => {
      if (res?.code === '0000' && res?.data?.fileUrls) {
        setPathList(res?.data?.fileUrls)
      }
    }).catch((err: any) => {
      console.log(err);
      Toast.show('获取发票失败');
    });
  }, [bbcShopId, orderId]);

  const downloadPdf = () => {
    if (copy(pathList[tabKey])) {
      Toast.show('已复制到剪切板');
    } else {
      Toast.show('复制失败');
    }
    setPdfVisible(false);
  };

  const handleTabChange = (key: string) => {
    setTabKey(key);
  };

  const handleFormSubmit = (pdfUrl: any) => {
    if (pdfUrl.trim() !== '') {
      loadPdfFromUrl(pdfUrl);
    } else {
      Toast.show('该链接无效');
    }
  };

  const loadPdfFromUrl = (url: any) => {
    pdfjsLib
      .getDocument(url)
      .promise.then((pdf: any) => {
        const pageNumbers = Array.from(new Array(pdf.numPages), (val, index) => index + 1);
        return Promise.all(pageNumbers.map((num: any) => pdf.getPage(num)));
      })
      .then((pages: any) => {
        const canvases = pages.map((page: any) => {
          const viewport = page.getViewport({ scale: 6 }); // 设置缩放比例
          const canvas = document.createElement('canvas');
          canvas.width = viewport.width;
          canvas.height = viewport.height;

          return page
            .render({
              canvasContext: canvas.getContext('2d'),
              viewport: viewport,
            })
            .promise.then(() => canvas.toDataURL('image/png')); // 转换为PNG格式
        });

        return Promise.all(canvases).then((screenshots: any) => {
          if (screenshots.length > 0) {
            setImageSrc(screenshots[0]); // 假设只处理第一页
            setImageViewerVisible(true); // 显示ImageViewer
          }
        });
      })
      .catch((reason: any) => {
        console.log('reason', reason);
      });
  };

  return (
    <div className={styles.main} style={floor.style} id={label}>
      <div className={styles.topBox}>
        {pathList.length > 1 && (
          <div className={styles.tabBox}>
            <CapsuleTabs
              className={styles.capsuTabs}
              defaultActiveKey="0"
              style={{ width: '100%' }}
              onChange={handleTabChange}
            >
              {pathList.map((item: any, index: any) => (
                <CapsuleTabs.Tab title={`发票 ${index + 1}`} key={index.toString()}>
                </CapsuleTabs.Tab>
              ))}
            </CapsuleTabs>
          </div>
        )}
        <PdfViewer
          file={pathList[tabKey]}
          renderType={'svg'}
          maxZoom={2}
          responseType={'arraybuffer'}
        />
        {/* Canvas不再使用 */}
        {/* <ImageViewer
          image={imageSrc}
          visible={imageViewerVisible}
          onClose={() => {
            setImageViewerVisible(false);
          }}
        /> */}
        <Modal
          visible={imageViewerVisible}
          content='长按保存图片到手机'
          image={imageSrc}
          closeOnMaskClick={true}
          onClose={() => {
            setImageViewerVisible(false);
          }
          }>
        </Modal>
      </div>
      <div className={styles.btnBox}>
        <Button onClick={() => handleFormSubmit(pathList[tabKey])}>下载图片</Button>
        <Button onClick={() => setPdfVisible(true)}>下载PDF</Button>
      </div>
      <Dialog
        visible={pdfVisible}
        content={'你需要复制PDF链接，在浏览器打开并下载文件'}
        title={'提示'}
        closeOnAction
        onAction={({ key }) => {
          if (key === 'confirm') {
            downloadPdf();
          } else if (key === 'onClose') {
            setPdfVisible(false);
          }
        }}
        actions={[
          [
            {
              key: 'onClose',
              text: '取消',
            },
            {
              key: 'confirm',
              text: '复制链接',
            },
          ],
        ]}
      />
    </div>
  );
};

export default BbcInvoiceDetail;  

